import os
import re
import traceback
import importlib
from .app import bot
from .sched import Scheduler
from .util import highlight_print

class Plugin:
    __slots__ = ('module', 'name', 'usage')

    def __init__(self, module, name='', usage=''):
        self.module = module
        self.name = name
        self.usage = usage

def load_plugin(module_name):
    try:
        module = importlib.import_module(module_name)
        name = getattr(module, '__plugin_name__', '')
        usage = getattr(module, '__plugin_usage__', '')
        bot.plugins.add(Plugin(module, name, usage))
        print(f'成功加载插件 {module_name}')
        return True
    except Exception as e:
        highlight_print(f'插件加载错误 {module_name}: {e}')
        highlight_print(traceback.format_exc(), fg_color=36)
        return False

def _load_plugins(plugin_dir, module_prefix):
    bot.plugins = set()
    for name in os.listdir(plugin_dir):
        path = os.path.join(plugin_dir, name)
        if os.path.isfile(path) and (name.startswith('_') or not name.endswith('.py')):
            continue
        if os.path.isdir(path) and (name.startswith('_') or not os.path.exists(os.path.join(path, '__init__.py'))):
            continue

        m = re.match(r'([_A-Z0-9a-z]+)(.py)?', name)
        if not m: continue

        load_plugin(f'{module_prefix}.{m.group(1)}')
    return len(bot.plugins)

def load_plugins(plugin_dir, module_prefix):
    bot.scheduler = Scheduler()
    bot.scheduler.remove_all_jobs()

    _load_plugins(plugin_dir, module_prefix)

    bot.scheduler.start()
